function [] = main_JumpBetaEst_Server(K,l)

%% This code estimates jump betas for each permno using a K-factor model.
%% The input data, stored in the folder Data_by_permno/, consists of historical 15-minute returns for each permno.
%% For each factor, the model includes two jump components, corresponding to large negative and large positive jumps.
%% These are defined over the size intervals [-inf, -0.005] and [0.005, inf], respectively.
%% The loop index `l` indicates the batch of permnos assigned to each server node, with a batch size of 200.
%% The resulting jump beta estimates are used as inputs for main_PremiaEst.m.


ReadPath = '../Data/Data_by_permno/'; % Sample files are included. Raw data are restricted and cannot be shared.
% Each file contains the full history of 15-minute returns for a single permno.
% Time 0 represents the close-to-open overnight return. 
% Time 1 to Time 26 are intraday 15-minute returns, covering the 6.5 trading hours of a standard day.


files = dir(fullfile(ReadPath, '*.mat'));

addpath('../Functions');

folderPath = ['./RESULTS_K_',num2str(K)];
if ~exist(folderPath, 'dir')
    mkdir(folderPath);
end

factors = load('../Data/factors.mat');

if K==4

   factors = factors.final_return_matrix(:,[1:5,8,6,7,9]);

else

   factors = factors.final_return_matrix;

end

startIdx = (200*(l-1)+1);
endIdx = min(200*l, length(files));

B_kl = repmat([-inf,-0.005;0.005,inf],K,1);
L_k = 2*ones(K,1);
un = 3;

for i = startIdx:endIdx
    disp(i)
    fileName = files(i).name;
    permno = sscanf(fileName, '%d');
    
    dataStruct = load(fullfile(ReadPath, fileName));
    data = dataStruct.data;
    
    [beta_J_hat, R2,beta_J_hat_tod, R2_tod, tod] = Jump_Beta(data, factors, L_k, B_kl, un);
    

    nDays     =      size(unique(data.date),1);
    n         =      size(data,1);
    nobs      =      n/nDays;
    Delta_n   =      1/252/(nobs-1);
    [~,~,todj] = fn_cont_ix_tod(un, 0.47, data.ret', Delta_n, nDays, nobs,[]);
    

    beta_J_hat = [permno, beta_J_hat];
    beta_J_hat_tod = [permno, beta_J_hat_tod];

    resultFile = fullfile(folderPath, [num2str(permno), '.mat']);
    save(resultFile, 'beta_J_hat', 'R2', 'L_k', 'B_kl', 'un','beta_J_hat_tod', 'R2_tod','tod','todj','K');
end
% The estimates for all permnos in the case of K = 6, computed using the server, are provided 
% and compressed in the RESULTS_K_6.zip file.
